<template>
  <div class="app-container">
    <div class="mb10">
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch">
        <div>
          <el-button size="mini" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </form-selections>
    </div>

    <div class="page-grid">
      <div class="action-group">
        <el-button v-action="'purchaseContract@changeAuditStatus'" size="small" type="primary" @click="bulkShipment">合同审核</el-button>
        <el-button v-action="'transhipmentOrder@save'" size="small" type="primary" @click="openList">转出运单</el-button>
        <el-button v-action="'purchaseContract@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
        <el-button v-action="'purchaseContract@uploadAttachment'" size="small" type="primary" @click="openUploadFileDialog">上传合同附件</el-button>
      </div>
      <div v-loading="loading">
        <egrid
          class="egrid"
          stripe
          fit
          border
          highlight-current-row
          element-loading-text="正在努力加载中..."
          :column-type="['selection']"
          :screen-heigh="screenHeigh"
          :data="tableData"
          :columns="columns"
          :columns-schema="columnsSchema"
          :columns-handler="columnsHandler"
          @selection-change="checkIds"
        />
        <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
      </div>
    </div>
    <!-- 新增供应商 -->
    <el-dialog
      v-if="dialogAddVisible"
      v-loading.lock="loading"
      v-loading="loading"
      :title="title"
      :visible.sync="dialogAddVisible"
      :close-on-click-modal="false"
      width="60%"
      class="dialogText header-none"
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      center
    >
      <el-form v-if="dialogAddVisible" ref="form" :model="form" label-width="90px">
        <div class="minheight-400">
          <el-row>
            <mainTilte title="合同主体信息" :left-title="allAmount" />
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="需方">
                <el-input v-model.trim="form.company_name" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="地址">
                <el-input v-model.trim="form.company_address" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人">
                <el-input v-model.trim="form.company_contacts" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电话">
                <el-input v-model.trim="form.company_mobile" disabled />
              </el-form-item>
            </el-col>
            <div class="underLine" />
            <el-col :span="8">
              <el-form-item label="供方">
                <el-input v-model.trim="form.supply.name" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="地址">
                <el-input v-model.trim="form.supply.address" disabled />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系人">
                <el-input v-model.trim="form.supply.contacts" disabled />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="电话">
                <el-input v-model.trim="form.supply.phone" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="签订日期">
                <el-input v-model.trim="form.created_at" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <mainTilte title="清单商品明细信息" />
          </el-row>
          <el-table :data="form.products" stripe fit border class="mb24">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-table :data="scope.row.package" fit border :stripe="false">
                  <el-table-column prop="name" label="名称" min-width="100" />
                  <!-- <el-table-column prop="number" label="数量" min-width="100" /> -->
                  <el-table-column prop="length" label="尺寸公制(长)" min-width="100" />
                  <el-table-column prop="width" label="尺寸公制(宽)" min-width="100" />
                  <el-table-column prop="height" label="尺寸公制(高)" min-width="100" />
                  <el-table-column prop="volume" label="体积" min-width="100" />
                  <el-table-column prop="length_AS" label="尺寸美制(长)" min-width="100" />
                  <el-table-column prop="width_AS" label="尺寸美制(宽)" min-width="100" />
                  <el-table-column prop="height_AS" label="尺寸美制(高)" min-width="100" />
                  <!-- <el-table-column prop="volume_AS" label="体积(美制)" min-width="100" /> -->
                  <el-table-column prop="volume_weight_AS" label="体积重(美制)" min-width="100" />
                  <el-table-column prop="weight_gross_AS" label="毛重(美制)" min-width="100" />
                  <el-table-column prop="weight_AS" label="净重(美制)" min-width="100" />
                  <el-table-column prop="oversize" label="Oversize" min-width="100" />
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="缩略图" width="150" align="center">
              <template slot-scope="scope">
                <thund :img="scope.row.goods_pic" />
              </template>
            </el-table-column>
            <el-table-column prop="goods_code" label="系统sku" width="180" align="center" />
            <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
            <el-table-column prop="goods_name_en" label="英文名称" width="180" align="center" />
            <el-table-column prop="number" label="采购数量" width="180" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.number }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="采购单价" width="180" align="center" />
            <el-table-column prop="amount" label="采购金额" width="180" align="center" />
            <el-table-column prop="arrive_date" label="交货日期" width="180" align="center">
              <template slot-scope="scope">
                {{ scope.row.arrive_date | formatDate('{y}-{m}-{d}') }}
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" width="180" align="center" />
          </el-table>
          <el-row>
            <mainTilte title="清单配件明细信息" />
          </el-row>
          <el-table :data="form.parts" stripe fit border class="mb24">
            <el-table-column label="缩略图" width="150" align="center">
              <template slot-scope="scope">
                <thund :img="scope.row.goods_pic" />
              </template>
            </el-table-column>
            <el-table-column prop="goods_code" label="系统sku" align="center" />
            <el-table-column prop="goods_name" label="中文名称" align="center" />
            <el-table-column prop="number" label="采购数量" width="180" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.number }}</p>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <mainTilte title="合同条款" />
          </el-row>
          <div>
            <ckEditor :past-editor.sync="form.content" :is-read-only="true" />
          </div>
        </div>
        <div>
          <el-row>
            <mainTilte title="审核" />
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="">
                <el-radio-group v-model="form.audit_status">
                  <el-radio :label="1">通过</el-radio>
                  <el-radio :label="-1">驳回</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item v-if="form.audit_status === -1" label="驳回原因" prop="audit_notes" :rules="notesRules">
                <el-input v-model="form.audit_notes" type="textarea" autosize />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取消审核</el-button>
        <el-button type="primary" :loading="formBtnLoading" @click="saveData()">确认审核</el-button>
      </span>
    </el-dialog>
    <contractWayBillList ref="waybillList" />
    <uploadFileDialog ref="uploadFileDialog" />
    <!--下载字段选择-->
    <DownModul :url="exportUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="导出字段选择" :options-modul="optionsModul" />
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import dicValues from '@/components/dicTransform/index'
import codeItem from '@/components/base/code'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import thund from '@/components/base/thund'
import ContractWayBillList from './components/contractWayBillList'
import appText from '@/components/appText/index'
// import { downloadxlsx } from '@/utils/index'
import uploadFileDialog from './components/uploadFileDialog'
import cacheList from '@/layout/mixin/cacheList'
import DownModul from '@/components/DownModul/index.vue'

export default {
  name: 'PurchaseContract',
  components: { ContractWayBillList, thund, uploadFileDialog, DownModul },
  directives: {
    action
  },
  mixins: [list, cacheList],
  data() {
    const DICTIONARIES = {
      auditStatus: [
        // 审核状态，0-未审核 1-已审核 -1 审核驳回
        {
          code: 0,
          name: '未审核'
        },
        {
          code: 1,
          name: '审核通过'
        },
        {
          code: -1,
          name: '审核驳回'
        }
      ],
      // 转出运状态 0-待出运 1-部分出运 -2 已出运
      cooperationStatus: [
        { code: 0, name: '待出运' },
        {
          code: 1,
          name: '部分出运'
        },
        {
          code: 2,
          name: '已出运'
        }
      ]
    }
    return {
      componentName: 'PurchaseContract',
      exportLoading: false,
      allAmount: '',
      value: '',
      value1: [],
      loading: false,
      dialogAddVisible: false, // 新增供应商弹框
      title: '',
      loadingText: '',
      rule: {},
      /** *
       * 定义搜索框
       */
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        pageSizeX: [10, 20, 30, 40, 50, 100], // 每页显示个数选择器的选项设置
        value: '',
        type: '',
        audit_status: ''
      },
      isActive: false,
      formItems: [
        {
          label: '合同编码',
          key: 'code',
          type: 'input',
          placeholder: '请输入合同编码'
        },
        {
          label: '供应商名称',
          key: 'supply_name',
          type: 'input',
          placeholder: '请输入供应商名称'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '未审核'
            },
            {
              value: 1,
              label: '审核通过'
            },
            {
              value: -1,
              label: '审核驳回'
            }
          ]
        }
      ],
      /** *
       * 定义显示的表格
       */
      columns: [
        {
          label: '合同编码',
          prop: 'code',
          minWidth: '200',
          align: 'center',
          tooltip: false,
          component: codeItem,
          propsHandler: function({ row, col, column }) {
            return {
              code: row.code ? row.code : '',
              routePath: '/supplyChain/purchaseContract/contractDetails',
              queryData: { id: row.id }
            }
          }
        },
        {
          label: '所属供应商',
          prop: 'supply_name',
          minWidth: '100',
          align: 'center',
          tooltip: false
        },
        // {
        //   label: '采购总金额',
        //   prop: 'amount',
        //   width: '100',
        //   align: 'center',
        //   tooltip: false
        // },

        {
          label: '审核状态',
          prop: 'audit_status',
          minWidth: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核原因',
          prop: 'audit_notes',
          minWidth: '100',
          align: 'center',
          component: appText,
          propsHandler({ row }) {
            return { text: row.audit_notes }
          }
        },
        {
          label: '出运状态',
          prop: 'transshipment',
          minWidth: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '采购员',
          prop: 'buyer',
          minWidth: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'created_by_name',
          minWidth: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          minWidth: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'updated_by_name',
          minWidth: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          minWidth: '200',
          align: 'center',
          tooltip: false
        }
      ],
      /** *
       * 字典表组件
       */
      columnsSchema: {
        审核状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['auditStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        出运状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['cooperationStatus'],
              code: row[col.prop],
              clickAbled: true,
              id: row.id
            }
          },
          listeners: {
            click: this.showWaybillList
          },
          component: dicValues
        }
      },
      issignContract: [
        {
          name: '合同编码',
          code: 'code'
        },
        // {
        //   name: '采购单号',
        //   code: 'purchase_order_code'
        // },
        {
          name: '供应商名称',
          code: 'supply_name'
        }
      ],
      statusList: [
        {
          code: 0,
          name: '未审核'
        },
        {
          code: 1,
          name: '审核通过'
        },
        {
          code: -1,
          name: '审核驳回'
        }
      ],
      form: {
        id: null,
        supplierCode: null, // 供应商代码
        supplierName: null, // 供应商名称
        settlementCycle: null, // 结算周期
        buyer: null, // 采购员
        contacts: '', // 联系人
        phone: null, // 联系人手机
        fixedTelephone: null, // 固定电话
        fax: null, // 传真
        // address: null, // 地址
        postcode: null, // 邮编
        payment: null, // 预付款比例
        notes: null, // 备注说明
        demand_info: {},
        supply: {},
        audit_status: 1,
        audit_notes: ''
      },
      notesRules: [
        { required: true, message: '请输入审核意见', trigger: 'blur' },
        { max: 500, message: '审核意见必须在500个字符以内', trigger: 'blur' }
      ],
      formBtnLoading: false,
      loadingBare: false,
      cachePaths: [
        '/supplyChain/purchaseContract/outWaybill/',
        '/supplyChain/purchaseContract/modifyContract',
        '/supplyChain/purchaseContract/contractDetails'
      ],
      exportUrl: '/purchase-contract/export',
      formVisibleDown: false,
      downLoadParams: {},
      optionsModul: [
        {
          key: 'id',
          label: 'ID'
        },
        {
          key: 'code',
          label: '合同编码'
        },
        {
          key: 'supply_name',
          label: '所属供应商'
        },
        {
          key: 'amount',
          label: '采购总金额'
        },
        {
          key: 'audit_status_text',
          label: '审核状态'
        },
        {
          key: 'transshipment_text',
          label: '转出运状态'
        },
        {
          key: 'created_by_name',
          label: '创建人'
        },
        {
          key: 'created_at',
          label: '创建时间'
        }
      ]
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    // /purchase-contract?supply_name=&code=&purchase_order_code=
    this.query()
  },
  activated() {
    console.log('======activated=====')
    this.query()
  },
  methods: {
    // 打开上传附件弹窗
    openUploadFileDialog() {
      const vm = this
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('最少选择一条数据')
        return false
      } else if (dataLength > 1) {
        this.$message.error('最多选择一条数据')
        return false
      } else if (this.checkedList[0].audit_status !== 1) {
        return this.$message.error('选择数据必须是已审核通过的')
      }

      vm.$refs.uploadFileDialog.show(this.checkedList[0])
    },
    // 导出
    handleExport() {
      const vm = this
      const { supply_name, code, audit_status } = vm.searchParams
      const params = {
        audit_status,
        code,
        supply_name
      }
      // if (type) {
      //   params[type] = value
      // }
      // vm.handleExportxlsx(vm.exportUrl, params)
      vm.downLoadParams = params
      vm.formVisibleDown = true
    },
    // 导出
    // handleExport() {
    //   const vm = this
    //   // vm.formVisibleDown = true
    //   vm.exportLoading = true
    //   const url = '/purchase-contract/export'
    //   const { type, value, audit_status } = vm.searchParams
    //   const params = {
    //     audit_status
    //   }
    //   if (type) {
    //     params[type] = value
    //   }
    //   vm.$http.post(url, params).then(res => {
    //     downloadxlsx(res.data)
    //     vm.exportLoading = false
    //   }).catch(() => {
    //     vm.exportLoading = false
    //   })
    // },
    // 显示出运单列表
    showWaybillList(id) {
      const vm = this
      vm.$refs.waybillList.show(id)
    },
    handleSearch() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.searchParams.page = 1
      vm.searchParams.limit = 10
      vm.searchParams.code = ''
      vm.searchParams.supply_name = ''
      vm.searchParams.audit_status = ''
      vm.query()
    },
    bulkShipment() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('最少选择一条数据')
        return false
      } else if (dataLength > 1) {
        this.$message.error('最多选择一条数据')
        return false
      }
      this.getDetailsData()
      this.dialogAddVisible = true
    },
    async getDetailsData() {
      await this.$http
        .get(`/purchase-contract/${this.ids[0]}`)
        .then((res) => {
          if (res.code === 10000) {
            this.form = Object.assign({}, res.data)
            this.form.audit_status = 1
            this.allAmount = '采购总金额:' + res.data.amount
            this.form.products.forEach((element) => {
              element['picture'] = element.goods_pic
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 新增-保存
    saveData() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.formBtnLoading = true
          const params = {
            id: vm.ids[0],
            audit_status: vm.form.audit_status,
            audit_notes: vm.form.audit_notes
          }
          vm.$http
            .post(`/purchase-contract/change-audit-status`, params)
            .then((res) => {
              vm.$message.success('审核成功')
              vm.dialogAddVisible = false
              vm.query()
              vm.formBtnLoading = false
            })
            .catch(() => {
              vm.formBtnLoading = false
            })
        }
      })
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          // 转出运状态 0-待出运
          const isShowHandler = [0, -1].includes(row.audit_status)
          return {
            row: row,
            edit: isShowHandler,
            del: false,
            editAction: 'purchaseContract@update'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          // 点击编辑
          editTableClick(row) {
            that.$router.push({
              path: '/supplyChain/purchaseContract/modifyContract',
              query: { id: row.id }
            })
          }
        }
      })
    },
    openList() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      if (dataLength > 1) {
        this.$message.error('最多选择一条数据')
        return false
      }
      if (this.checkedList[0].audit_status !== 1) {
        return this.$message.error('请选择已审核通过的数据')
      }
      // 已出运
      if (this.checkedList[0].transshipment === 2) {
        this.$message.error('已出运,请选择其他数据')
        return false
      }
      this.$confirm('确认要将选中的采购合同进行转出运单吗？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const id = this.checkedList[0].id
          window.localStorage.removeItem('outWaybillData')
          this.$router.push({
            path: `/supplyChain/purchaseContract/outWaybill/${id}`
          })
        })
        .catch((action) => { })
    },
    handleSizeChange(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.searchParams.page = val
      this.query()
    },
    query() {
      let url = '/purchase-contract'
      const { page, limit, code, supply_name, audit_status } = this.searchParams
      url += `?page=${page}&limit=${limit}&audit_status=${audit_status}`
      if (code) {
        url += `&code=${code}`
      }
      if (supply_name) {
        url += `&supply_name=${supply_name}`
      }
      this.initTableData(url)
    }
  }
}
</script>

<style lang="scss" scoped>
.minheight-400 {
  height: 400px;
  overflow-y: auto;
}
.cooperaion-status {
  color: #5c90d2;
  cursor: pointer;
}
</style>
